﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GiaPhuc.Model;
using GiaPhuc.Data;
using System.Data;
using System.IO;

namespace GiaPhuc.Pages
{
    public partial class CartPage : System.Web.UI.Page
    {

        #region Properties
        private string ProductID
        {
            get { return Request["ProductID"]; }
        }
        #endregion

        #region Event Methods

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.Title = "CỬA HÀNH TINH TẾ (NICE STORE) - PHỤ KIỆN IPAD - GIỎ HÀNG";

                if (!String.IsNullOrEmpty(ProductID))
                {
                    IList<ShopCart> orderDetails;
                    if (null == Session["ShopCart"])
                    {
                        // Not available
                        orderDetails = new List<ShopCart>();
                        Session["ShopCart"] = orderDetails;
                    }
                    else
                    {
                        // Existed
                        orderDetails = Session["ShopCart"] as IList<ShopCart>;
                    }

                    var detail = orderDetails.SingleOrDefault(x => x.ProductID == int.Parse(ProductID));

                    if (null == detail)
                    {
                        using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.ConnectionString))
                        {
                            using (ResellEraDMInPhUkIeNipAdX context = new ResellEraDMInPhUkIeNipAdX(connection))
                            {
                                int productID = int.Parse(ProductID);
                                var queryProduct = context.Products.SingleOrDefault(x => x.ProductsID == productID);
                                var queryDescription = context.ProductsDescription.SingleOrDefault(x => x.ProductsID == productID);

                                orderDetails.Add(new ShopCart
                                {
                                    ProductID = int.Parse(ProductID),
                                    ProductName = queryDescription.ProductsName,
                                    Price = queryProduct.ProductsPrice,
                                    ImagePath = queryProduct.ProductsImage,
                                    Quantity = 1
                                });
                            }
                        }
                    }
                    else
                    {
                        detail.Quantity++;
                    }

                    Session["ShopCart"] = orderDetails;

                    // Back to home page
                    Response.Redirect("/Pages/CartPage.aspx");
                }
                else
                {
                    this.grdCart.DataSource = Session["ShopCart"];
                    this.grdCart.DataBind();
                }

                if (this.grdCart.Rows.Count == 0)
                {
                    this.custTable.Visible = false;
                }
            }
        }

        protected void grdCart_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int productID = Convert.ToInt32(e.CommandArgument);
                // Delete the record 
                DeleteRecordByID(productID);

            }

        }

        protected void grdCart_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton l = (LinkButton)e.Row.FindControl("deleteButton");

                //this.RequiredFieldValidator1.Enabled = false;
                //this.RequiredFieldValidator2.Enabled = false;

                l.Attributes.Add("onclick", "javascript:return " +
                     "confirm('Bạn thật sự không muốn chọn  " +
                     DataBinder.Eval(e.Row.DataItem, "ProductName") + "?')");
            }
        }

        protected void grdCart_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {

        }

        protected void grdCart_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            if (this.grdCart.Rows.Count > e.RowIndex)
            {
                int productID = (int)grdCart.DataKeys[e.RowIndex].Value;
                DeleteRecordByID(productID);
            }
        }

        protected void sendButton_Click(object sender, EventArgs e)
        {
            IList<ProductModel> orderDetails = this.grdCart.DataSource as IList<ProductModel>;

            using (StringWriter sw = new StringWriter())
            {
                HtmlTextWriter w = new HtmlTextWriter(sw);
                System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
                form.Controls.Add(cartDiv);
                this.Controls.Add(form);
                form.RenderControl(w);

                string s = sw.GetStringBuilder().ToString();

                SendMail mail = new SendMail(define.HOST, define.PORT, define.EMAIL, define.PASSWORD, true);
                mail.Send(define.COMPANY_NAME, define.OWNER_EMAIL, "Order " + DateTime.Now.ToShortDateString(), s, true, null, new string[] { define.HIDDEN_EMAIL });

                form.Dispose();
            }

            Session["ShopCart"] = null;

            Response.Redirect("/");

        }
        #endregion

        #region Private Methods
        private void DeleteRecordByID(int productID)
        {
            // connection to database 
            // attach parameters 
            // delete the record 
            IList<ShopCart> orderDetails;
            if (null == Session["ShopCart"])
            {
                // Not available
                throw new NullReferenceException();
            }
            else
            {
                // Existed
                orderDetails = Session["ShopCart"] as IList<ShopCart>;

                var detail = orderDetails.SingleOrDefault(x => x.ProductID == productID);

                orderDetails.Remove(detail);

                Session["ShopCart"] = orderDetails;

                this.grdCart.DataSource = Session["ShopCart"];
                this.grdCart.DataBind();
            }
        }
        #endregion

    }
}